import 'dart:async';

import 'package:PLDroidMediaStreaming/PLDroidMediaStreamingView.dart';
import 'package:PLDroidMediaStreaming/controller/MediaStreamingManager.dart';
import 'package:PLDroidMediaStreaming/main.dart';
import 'package:PLDroidMediaStreaming/model/StreamingProfile/StreamingProfile.dart';
import 'package:flutter/material.dart';

import 'package:PLDroidMediaStreaming/PLDroidMediaStreaming.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  String publishURL = "rtmp://push-live.17ued.club/footish/20200709?auth_key=1594293487-0-0-465a7850fc275e61b2f8233e3bd83db0";
  StreamSubscription<dynamic> subscription;

  Widget child;
  MediaStreamingManager manager;

  @override
  void initState() {
    child = Container();
    manager = MediaStreamingManager(
      streamingProfile: StreamingProfile(
        aQuality: StreamingProfile.AUDIO_QUALITY_MEDIUM2,
        vQuality: StreamingProfile.VIDEO_QUALITY_HIGH1,
        videoEncodingSize: VideoEncodingSize(
          level: StreamingProfile.VIDEO_ENCODING_HEIGHT_480
        ),
        publishUrl: publishURL
      ),
      cameraStreamingSetting: CameraStreamingSetting(
        cameraId: CAMERA_FACING_ID.CAMERA_FACING_FRONT,
        continuousFocusModeEnabled: true,
        cameraPreviewSize: CameraPreviewSize(
          level: PREVIEW_SIZE_LEVEL.MEDIUM,
          ratio: PREVIEW_SIZE_RATIO.RATIO_16_9
        ),
      )
    );
    initView();
    super.initState();
  }

  @override
  void dispose() { 
    manager.destroy();
    subscription?.cancel();
    super.dispose();
  }

  initView() async {
    Map<Permission, PermissionStatus> map = await [
      Permission.camera,
      Permission.storage,
      Permission.microphone,
    ].request();

    if(
      map[Permission.camera].isGranted &&
      map[Permission.storage].isGranted &&
      map[Permission.microphone].isGranted 
    ) {
      setState(() {
        child = PLDroidMediaStreamingView(
          manager: manager,
        );
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('直播示例'),
        ),
        body: Center(
          child: Container(
            child: child
          )
        ),
      ),
    );
  }
}
